import RecorderCore from "recorder-core";
import "recorder-core/src/engine/wav.js";
import wx from "weixin-js-sdk";
import {
	getMemberConfig,
	wexinUploadOss
} from "../common/api/aivoice.js";
let isRecording = false;

function WxRecorder(options = {}) {
	if (
		!options.appId ||
		!options.timestamp ||
		!options.nonceStr ||
		!options.signature
	) {
		console.error("微信配置失败");
	}

	wx.config({
		true: options.debug || false,
		appId: options.appId,
		timestamp: options.timestamp,
		nonceStr: options.nonceStr,
		signature: options.signature,
		jsApiList: options.jsApiList || [
			"startRecord",
			"stopRecord",
			"onVoiceRecordEnd",
			"uploadVoice",
		],
	});
	console.log(options);
	let sTime = 0;

	const instance = {
		isWx: true,
		open: (successFn, failFn) => {
			wx.ready(() => {
				options.onReady?.();
				console.log("options", options);
				wx.startRecord({
					success: () => {
						isRecording = true;
						successFn?.();
					},
					cancel: () => failFn?.("用户取消了录音"),
				});

				// wx.startRecord({
				// 	success(res) {
				// 		console.log("res", res);
				// 		console.log("successFn", successFn);
				// 	},
				// 	fail(err) {
				// 		console.log("err", err);
				// 		console.log("errfn", successFn);
				// 	},
				// });
			});
		},
		start: (timeoutStopSuccessFn, timeoutStopFailFn) => {
			sTime = Date.now();
			console.log("开始录音了吗开始录音");
			// 录音不能超过一分钟 超过一分钟自动停止 并触发该事件
			wx.onVoiceRecordEnd({
				complete: res => {
					console.log("录音不能超过一分钟");
					uploadVoice(res.localId)
						.then((blob, duration) =>
							timeoutStopSuccessFn?.(blob, duration)
						)
						.catch(msg => timeoutStopFailFn?.(msg));

					instance.close();
				},
			});
		},
		stop: (successFn, failFn) => {
			console.log("isRecording", isRecording);
			if (isRecording) {
				wx.stopRecord({
					success: res => {
						console.log("isRecording81", isRecording);
						isRecording = false;
						console.log("isRecording83", isRecording);
						uploadVoice(res.localId)
							.then((blob, duration) =>
								successFn?.(blob, duration)
							)
							.catch(msg => failFn?.(msg));
					},
					fail: res => {
						console.log("failFn", res);
						failFn?.(res.errMsg);
					},
				});
			} else {
				console.log("没有开始录音");
			}

			instance.close();
		},
		close: () => {
			sTime = 0;
		},
	};

	function uploadVoice(localId) {
		return new Promise((resolve, reject) => {
			wx.uploadVoice({
				localId, // 需要上传的音频的本地ID，由stopRecord接口获得
				isShowProgressTips: 1, // 默认为1，显示进度提示
				success: res => {
					var serverId = res.serverId;
					console.log("微信文件地址serverId：", serverId);
					wexinUploadOss({
						media_id: serverId,
						member_id: options.member_id
					}).then((res) => {
						if (res.code == 1 && res.data.file) {
							fetch(res.data.file)
								.then((r) => r.blob())
								.then((blob) => resolve(blob, Date.now() - sTime));
						} else reject('录音失败，请稍后再试');
					});
				},
			});
		});
	}

	return instance;
}

export default function Recorder(options) {
	// IOS微信公众号内核不支持录音
	if (/iphone.*micromessenger/i.test(navigator.userAgent))
		return WxRecorder(options);
	return RecorderCore(options);
}